<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"adoontheway.gitee.io","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="Nodejs与C++通讯加密调研">
<meta property="og:type" content="article">
<meta property="og:title" content="cryptjs vs crypto++ 加解密(上篇)">
<meta property="og:url" content="https://adoontheway.gitee.io/2019/07/09/aesandrsa/index.html">
<meta property="og:site_name" content="Ados">
<meta property="og:description" content="Nodejs与C++通讯加密调研">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-07-09T03:01:23.000Z">
<meta property="article:modified_time" content="2023-05-25T10:26:16.018Z">
<meta property="article:author" content="ado">
<meta property="article:tag" content="c++">
<meta property="article:tag" content="aes">
<meta property="article:tag" content="rsa">
<meta property="article:tag" content="nodejs">
<meta property="article:tag" content="websocket">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://adoontheway.gitee.io/2019/07/09/aesandrsa/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>cryptjs vs crypto++ 加解密(上篇) | Ados</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Ados</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">a fullstack game worker</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/adoontheway" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="external nofollow noopener noreferrer" target="_blank"><svg width="80" height="80" viewbox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://adoontheway.gitee.io/2019/07/09/aesandrsa/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="ado">
      <meta itemprop="description" content="me, robot.">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ados">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          cryptjs vs crypto++ 加解密(上篇)
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-07-09 11:01:23" itemprop="dateCreated datePublished" datetime="2019-07-09T11:01:23+08:00">2019-07-09</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2023-05-25 18:26:16" itemprop="dateModified" datetime="2023-05-25T18:26:16+08:00">2023-05-25</time>
              </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
            <div class="post-description">Nodejs与C++通讯加密调研</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="Preface"><a href="#Preface" class="headerlink" title="Preface"></a>Preface</h1><p>接着调研WebSocket通讯协议加密的事宜。</p>
<p>做法是：</p>
<ul>
<li>协议加密使用AES</li>
<li>AES的密钥由RSA加密之后进行传递</li>
<li>前后端各自生成自己的密钥对，然后交换各自的公钥</li>
<li>用自己的私钥加密数据，对方则用公钥解密</li>
</ul>
<h1 id="Reference"><a href="#Reference" class="headerlink" title="Reference"></a>Reference</h1><ul>
<li><a target="_blank" rel="external nofollow noopener noreferrer" href="https://www.cnblogs.com/huanzi-qch/p/10913636.html">前后端API交互数据加密——AES与RSA混合加密完整实例</a></li>
<li><a target="_blank" rel="external nofollow noopener noreferrer" href="https://www.cnblogs.com/huanzi-qch/p/11010153.html">WebSocket数据加密——AES与RSA混合加密</a></li>
<li><a target="_blank" rel="external nofollow noopener noreferrer" href="https://github.com/travist/jsencrypt">jsencrypt</a></li>
<li><a target="_blank" rel="external nofollow noopener noreferrer" href="https://github.com/travist/jsencrypt/issues/21">Rhino support? #21</a></li>
<li><a target="_blank" rel="external nofollow noopener noreferrer" href="https://linux.die.net/man/3/rsa_private_decrypt">openssl API : rsa_private_decrypt</a></li>
</ul>
<h1 id="Contents"><a href="#Contents" class="headerlink" title="Contents"></a>Contents</h1><h2 id="前端"><a href="#前端" class="headerlink" title="前端"></a>前端</h2><h3 id="RSA库"><a href="#RSA库" class="headerlink" title="RSA库"></a>RSA库</h3><p>前端加密用的是 jsencrypt,使用的版本是2.3.0， 官网的tag里面最新的版本是3.0.0rc，愿意做小白鼠的可以去试一下：</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm i --save jsencrypt@2.3.0</span><br></pre></td></tr></table></figure>

<p>需要注意的是，我们这个的<strong>nodejs</strong> <em>native<em>里用的，而不是在浏览器中使用，所以*</em>jsencrypt**只要导入进来，就会报 <u>navigator is not defined</u> 的问题，这个时候，需要去 *jsencrypt.js</em> 中修改一下源代码，参考的是 <strong>jsencrypt</strong> 在 github上的 <a target="_blank" rel="external nofollow noopener noreferrer" href="https://github.com/travist/jsencrypt/issues/21">issue #21</a>，也就是上面的第四条参考。</p>
<p>首先，去第73行左右，也就是初始运行会报错的地方的前面加上以下代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>( <span class="keyword">typeof</span> <span class="built_in">window</span> === <span class="string">&#x27;undefined&#x27;</span> )</span><br><span class="line">  <span class="keyword">var</span> <span class="built_in">window</span> = &#123;&#125;;</span><br><span class="line"><span class="keyword">if</span>( <span class="keyword">typeof</span> navigator === <span class="string">&#x27;undefined&#x27;</span> )</span><br><span class="line">  <span class="keyword">var</span> navigator = &#123;&#125;;</span><br></pre></td></tr></table></figure>

<p>加上这个之后 run 这里是不会报错了，但是在另一个地方会报错，也就是第3850左右，即 <code>ASN1.prototype.getHexStringValue = function ()</code> ,这里只需要将 <strong>ASN1</strong> 改为 <strong>window.ASN1</strong>就可以了。</p>
<h3 id="AES库"><a href="#AES库" class="headerlink" title="AES库"></a>AES库</h3><p>照旧，CryptJS</p>
<h3 id="测试用例"><a href="#测试用例" class="headerlink" title="测试用例"></a>测试用例</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">var</span> rsaUtil = &#123;</span><br><span class="line">    bits : <span class="number">1024</span>,</span><br><span class="line">    thisKeyPair : &#123;&#125;,</span><br><span class="line">    genKeyPair : <span class="function"><span class="keyword">function</span> (<span class="params">bits=rsaUtil.bits</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> genKeyPair = &#123;&#125;;</span><br><span class="line">        rsaUtil.thisKeyPair = <span class="keyword">new</span> JSEncrypt(&#123;<span class="attr">default_key_size</span>: bits,<span class="attr">log</span>:<span class="literal">true</span>&#125;);</span><br><span class="line">        genKeyPair.privateKey = rsaUtil.thisKeyPair.getPrivateKey();</span><br><span class="line">        genKeyPair.publicKey = rsaUtil.thisKeyPair.getPublicKey();</span><br><span class="line">        <span class="keyword">return</span> genKeyPair;</span><br><span class="line">    &#125;,</span><br><span class="line">    encrypt : <span class="function"><span class="keyword">function</span> (<span class="params">plaintext, publickey</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>( plaintext <span class="keyword">instanceof</span> <span class="built_in">Object</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="built_in">Error</span>(<span class="string">&#x27;invalid content, String only&#x27;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// publickey &amp;&amp; rsaUtil.thisKeyPair.setPublicKey(publickey);</span></span><br><span class="line">        <span class="keyword">return</span> rsaUtil.thisKeyPair.encrypt(plaintext)</span><br><span class="line">    &#125;,</span><br><span class="line">    decrypt : <span class="function"><span class="keyword">function</span> (<span class="params">ciphertext, privatekey</span>) </span>&#123;</span><br><span class="line">        <span class="comment">// privatekey &amp;&amp; rsaUtil.thisKeyPair.setPrivateKey(privatekey);</span></span><br><span class="line">        <span class="keyword">let</span> decstring = rsaUtil.thisKeyPair.decrypt(ciphertext);</span><br><span class="line">        <span class="keyword">return</span> decstring;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">testRsa</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> text = <span class="string">&#x27;没纸了&#x27;</span>;</span><br><span class="line">    <span class="keyword">let</span> keypair = rsaUtil.genKeyPair();</span><br><span class="line">    <span class="keyword">let</span> ciphertext = rsaUtil.encrypt(text,keypair.publicKey);</span><br><span class="line">    <span class="keyword">let</span> plaintext = rsaUtil.decrypt(ciphertext,keypair.privateKey);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Private Key : &#x27;</span>, keypair.privateKey);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Public Key : &#x27;</span>, keypair.publicKey);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;CipherText : &#x27;</span>, ciphertext);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Decrypted Text : &#x27;</span>, plaintext);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">testRsa();</span><br></pre></td></tr></table></figure>

<p>Output:</p>
<blockquote>
<p>Private Key :  </p>
<p>—–BEGIN RSA PRIVATE KEY—– MIICWwIBAAKBgGsgGKaHUbFj5YnUpaF1o8dqReXJZWE4UpPZE3A8wzlU9W8A9xxs gee2CmJDmscvn9rAzABXDH6L4+bT+Xk4MbPHxW4XOxmWX4fAMyeIChZKqC1Z4CB1 M/h1EzXMLWqVOc3YQNFiJg/7Ftcc1uwlgsOZlXI068m3f+26eMKHew6lAgMBAAEC gYASd6wIOVfJ/vC5PCF5njAn1phKLtf9VJpXxpplRPRa09yj0ETJb6NNcMKFgiYS pJEoQwhoHpmWz0LwriZZ0Wgv3dyNVM9wloullMjAKhOIl6/piDUq03j+YWjI5i9h RzTeG584C7HmDLuA6q5/mA4o2seP8jLC+yPsoL+nGiLgQQJBAMja2QXImvWeSKlr LRO7HI9wnrY25c+BMAx3aNJhGF9pnIbleGJggbW2jKeB2h+wwcfaRzdEQn5/jX/W XJ4JTRkCQQCIiXB3Qj6vV4RqVu8yYMUuLT4PxfuBT/K57XTPjj97DjPvZSTRUn/v sLzhp62tOs5z9ZDqeA3F9ujkY2joW3NtAkEAs1ZUeEmJss1Fa5/6e6eR9LFFxMR3 pTNgR4FG4rE3JdoSnI+/UXeB2VHJfLcAn1MfcuZ+t+YGyRPyr7YitCjx4QJANnRq UIYxLgl/nFHT0Inb2pDcwbm6l1ZlflYAUo9vLgr6F66FQp7eu6AHlRAlKoPbt0/n XjxHcf8J35zuSE3A+QJAGgm81eV1c6uXhm94weDsmerv2LqViHporQjXM2/SdWNf biHNiiCg4jUqHHeMmqaGuLHdsBsCfQoN2Zxg2HtAKg== —–END RSA PRIVATE KEY—– </p>
<p>Public Key :  </p>
<p>—–BEGIN PUBLIC KEY—– MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgGsgGKaHUbFj5YnUpaF1o8dqReXJ ZWE4UpPZE3A8wzlU9W8A9xxsgee2CmJDmscvn9rAzABXDH6L4+bT+Xk4MbPHxW4X OxmWX4fAMyeIChZKqC1Z4CB1M/h1EzXMLWqVOc3YQNFiJg/7Ftcc1uwlgsOZlXI0 68m3f+26eMKHew6lAgMBAAE= —–END PUBLIC KEY—– </p>
<p>CipherText :  St8GeWQ8UlhItOC+6TwNOM2nb0j5SFQDyNZpbU0FE0HEfbWhWyTfYshjhLl9FdyDyb/uC/XTr779qjnaUycEFkswwxJAmHbfYB3YRFvkr+M8YmAJGthJYdgInXHZA5CgJEVgBbCs+EP0Rcv8vI1Plffa/vzHF41WS3E2dHL1dYs= </p>
<p>Decrypted Text :  没纸了</p>
</blockquote>
<p>这里需要注意的是，照抄那位大哥的代码，会出现加密和解释失败的问题，在新建JSEncrypt实例的时候，将log选项设置为true:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> JSEncrypt(&#123;<span class="attr">default_key_size</span>: bits,<span class="attr">log</span>:<span class="literal">true</span>&#125;);</span><br></pre></td></tr></table></figure>

<p>会发现，原先的代码里面的公钥和私钥都重复设置了：</p>
<blockquote>
<p>A key was already set, overriding existing.  jsencrypt.js:4216</p>
<p>A key was already set, overriding existing. jsencrypt.js:4216</p>
</blockquote>
<p>所以这里我把重新设置公私钥的地方都注释掉了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// publickey &amp;&amp; rsaUtil.thisKeyPair.setPublicKey(publickey);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// privatekey &amp;&amp; rsaUtil.thisKeyPair.setPrivateKey(privatekey);</span></span><br></pre></td></tr></table></figure>

<p>连接服务端的测试代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function">function <span class="title">testCPPRsa</span><span class="params">(params)</span> </span>&#123;</span><br><span class="line">    let keypair = rsaUtil.<span class="built_in">genKeyPair</span>();</span><br><span class="line">    let aeskey = aesUtil.<span class="built_in">genKey</span>();</span><br><span class="line">    let cryptedAeskey = rsaUtil.<span class="built_in">encrypt</span>(aeskey);</span><br><span class="line">    console.<span class="built_in">log</span>(<span class="string">&quot;AESKey : &quot;</span>, aeskey);</span><br><span class="line">    console.<span class="built_in">log</span>(<span class="string">&quot;AESKey after encrypt:&quot;</span>,cryptedAeskey);</span><br><span class="line">    let socket = <span class="keyword">new</span> net.<span class="built_in">Socket</span>(&#123;allowHalfOpen:<span class="literal">true</span>&#125;);</span><br><span class="line">    socket.<span class="built_in">setTimeout</span>(<span class="number">3000</span>);</span><br><span class="line">    socket.on(&#x27;timeout&#x27;,()=&gt;&#123;</span><br><span class="line">        <span class="comment">// console.log(&#x27;socket timeout&#x27;);</span></span><br><span class="line">        socket.<span class="built_in">end</span>();</span><br><span class="line">    &#125;);</span><br><span class="line">    socket.on(&#x27;connect&#x27;,()=&gt;&#123;</span><br><span class="line">        console.<span class="built_in">log</span>(<span class="string">&quot;Connected event...&quot;</span>);</span><br><span class="line">    &#125;);</span><br><span class="line">    socket.on(&#x27;ready&#x27;,() =&gt; &#123;</span><br><span class="line">        socket.<span class="built_in">setKeepAlive</span>(<span class="literal">true</span>);</span><br><span class="line">        <span class="comment">// console.log(&#x27;ready&#x27;);</span></span><br><span class="line">        let res = socket.<span class="built_in">write</span>(keypair.privateKey);</span><br><span class="line">        console.log(&#x27;Flushed0:&#x27;,res);</span><br><span class="line">        res = socket.<span class="built_in">write</span>(cryptedAeskey);</span><br><span class="line">        console.log(&#x27;Flushed1:&#x27;,res);</span><br><span class="line">        <span class="comment">// socket.end();</span></span><br><span class="line">        <span class="comment">// console.log(keypair.privateKey);</span></span><br><span class="line">        <span class="comment">// socket.write(cryptedAeskey);</span></span><br><span class="line">        <span class="comment">// socket.end();</span></span><br><span class="line">    &#125;);</span><br><span class="line">    socket.on(&#x27;end&#x27;,()=&gt;&#123;</span><br><span class="line">        console.log(&#x27;end&#x27;);</span><br><span class="line">        <span class="comment">// console.log(aeskey);</span></span><br><span class="line">        <span class="comment">// console.log(cryptedAeskey);</span></span><br><span class="line">        <span class="comment">// let res = socket.write(cryptedAeskey);</span></span><br><span class="line">        <span class="comment">// console.log(&#x27;Flushed1:&#x27;,res);</span></span><br><span class="line">    &#125;);</span><br><span class="line">    socket.on(&#x27;drain&#x27;,()=&gt;&#123;</span><br><span class="line">        console.log(&#x27;drain event&#x27;);</span><br><span class="line">    &#125;);</span><br><span class="line">    socket.connect(8888, &#x27;192.168.2.160&#x27;,()=&gt;&#123;</span><br><span class="line">        console.<span class="built_in">log</span>(<span class="string">&quot;Connected...&quot;</span>)</span><br><span class="line">    &#125;);   </span><br><span class="line">    socket.on(&#x27;error&#x27;, (err)=&gt;&#123;</span><br><span class="line">        console.<span class="built_in">error</span>(err);</span><br><span class="line">    &#125;);</span><br><span class="line">    socket.on(&#x27;close&#x27;,(evt)=&gt;&#123;</span><br><span class="line">        console.<span class="built_in">warn</span>(evt);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="服务端"><a href="#服务端" class="headerlink" title="服务端"></a>服务端</h2><p>接下来就是测试与服务端RSA算法的兼容性了。</p>
<p>服务端RSA用的是openssl的，遇到了一些问题：</p>
<p>main和上次差不多，还是用的boost::asio，只是上次的代码同一个socket同步读只会读一次，这一次将单个socket放到一个线程里面去操作了，代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>&#123;</span><br><span class="line">        boost::asio::io_service service_;</span><br><span class="line">        <span class="function">tcp::endpoint <span class="title">endpoint_</span><span class="params">(tcp::v4(), <span class="number">8888</span>)</span></span>;</span><br><span class="line">        <span class="function">tcp::acceptor <span class="title">acceptor_</span><span class="params">(service_, endpoint_)</span></span>;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;addr:&quot;</span> &lt;&lt; acceptor_.<span class="built_in">local_endpoint</span>().<span class="built_in">address</span>() &lt;&lt; endl;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;port:&quot;</span> &lt;&lt; acceptor_.<span class="built_in">local_endpoint</span>().<span class="built_in">port</span>() &lt;&lt; endl;</span><br><span class="line">        <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">            <span class="function">tcp::socket <span class="title">socket_</span><span class="params">(service_)</span></span>;</span><br><span class="line">            acceptor_.<span class="built_in">accept</span>(socket_);</span><br><span class="line">            cout &lt;&lt; <span class="string">&quot;client:&quot;</span> &lt;&lt; socket_.<span class="built_in">remote_endpoint</span>().<span class="built_in">address</span>() &lt;&lt; endl;</span><br><span class="line">            <span class="function">Client <span class="title">c</span><span class="params">(&amp;socket_)</span></span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">    &#125;<span class="built_in"><span class="keyword">catch</span></span>(std::exception&amp; e)&#123;</span><br><span class="line">        cerr &lt;&lt; <span class="string">&quot;Exception: &quot;</span> &lt;&lt; e.<span class="built_in">what</span>() &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">            </span><br></pre></td></tr></table></figure>

<p> 单个处理类的头文件：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> CLIENT_H</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> CLIENT_H</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;boost/asio.hpp&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;boost/thread.hpp&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;boost/date_time/posix_time/posix_time.hpp&gt;</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">using</span> boost::asio::ip::tcp;</span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="comment">//#define b64map &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/&quot;</span></span><br><span class="line"><span class="comment">//base64空位填充符</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> b64pad <span class="meta-string">&#x27;=&#x27;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Client</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="built_in">Client</span>(tcp::socket *sock);</span><br><span class="line">    ~<span class="built_in">Client</span>();</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Accept</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">RsaDecrypt</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="comment">// openssl自带的base64解密，似乎不成功</span></span><br><span class="line">    <span class="function"><span class="keyword">bool</span> <span class="title">base64Decode</span><span class="params">(<span class="keyword">const</span> string&amp; input, string&amp; output)</span></span>;</span><br><span class="line">    <span class="comment">// jsencrypt 的反解翻译</span></span><br><span class="line">    <span class="function">string <span class="title">b64tohex</span><span class="params">(<span class="keyword">const</span> string&amp; input)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    tcp::socket* sock;</span><br><span class="line">    string key ;<span class="comment">//RSA解密用的私钥</span></span><br><span class="line">    string content;<span class="comment">//需要解密的内容</span></span><br><span class="line">	<span class="comment">// base64字符集</span></span><br><span class="line">    <span class="keyword">const</span> string b64map = <span class="string">&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/&quot;</span>;</span><br><span class="line">    <span class="comment">// jsencrypt 要用到的字符集</span></span><br><span class="line">    <span class="keyword">const</span> string BI_RM = &#123;<span class="string">&quot;0123456789abcdefghijklmnopqrstuvwxyz&quot;</span>&#125;;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span> <span class="comment">// CLIENT_H</span></span></span><br></pre></td></tr></table></figure>

<p>client.cpp:</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&quot;Client.h&quot;</span></span></span><br><span class="line"><span class="comment">//#include &lt;thread&gt;</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;boost/thread.hpp&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;openssl/rsa.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;openssl/err.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;openssl/pem.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;openssl/err.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;openssl/ssl.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;boost/archive/iterators/base64_from_binary.hpp&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;boost/archive/iterators/binary_from_base64.hpp&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;boost/archive/iterators/transform_width.hpp&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line">Client::<span class="built_in">Client</span>(tcp::socket *sock_)</span><br><span class="line">&#123;</span><br><span class="line">    sock = sock_;</span><br><span class="line">    <span class="function">boost::thread <span class="title">th</span><span class="params">(boost::bind(&amp;Client::Accept,<span class="keyword">this</span>))</span></span>;</span><br><span class="line">    th.<span class="built_in">join</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Client::~<span class="built_in">Client</span>()</span><br><span class="line">&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Client::Accept</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">try</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">while</span>(<span class="literal">true</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="function">vector&lt;<span class="keyword">unsigned</span> <span class="keyword">char</span>&gt; <span class="title">buf</span><span class="params">(<span class="number">1024</span>)</span></span>;</span><br><span class="line">            <span class="keyword">size_t</span> s = sock-&gt;<span class="built_in">read_some</span>(boost::asio::<span class="built_in">buffer</span>(buf));</span><br><span class="line">            cout &lt;&lt; <span class="string">&quot;Read &quot;</span> &lt;&lt; s &lt;&lt;<span class="string">&quot;bytes from client complete.&quot;</span> &lt;&lt; endl;</span><br><span class="line">            <span class="function">string <span class="title">s1</span><span class="params">(buf.begin(),buf.begin()+s)</span></span>;</span><br><span class="line">            <span class="keyword">if</span>(key.<span class="built_in">size</span>() == <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                key = s1;</span><br><span class="line">            &#125;<span class="keyword">else</span></span><br><span class="line">            &#123;</span><br><span class="line"><span class="comment">//                content = s1;</span></span><br><span class="line"><span class="comment">//                base64Decode(s1,content);</span></span><br><span class="line">                content = <span class="built_in">b64tohex</span>(s1);</span><br><span class="line">                cout &lt;&lt; <span class="string">&quot;Key : &quot;</span> &lt;&lt; key &lt;&lt; endl;</span><br><span class="line">                cout &lt;&lt; <span class="string">&quot;Content : &quot;</span> &lt;&lt; content &lt;&lt; endl;</span><br><span class="line">                <span class="built_in">RsaDecrypt</span>();</span><br><span class="line">            &#125;</span><br><span class="line"><span class="comment">//            string ss(buf.begin(), buf.begin()+s);</span></span><br><span class="line"><span class="comment">//            cout &lt;&lt; ss &lt;&lt; endl;</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;<span class="built_in"><span class="keyword">catch</span></span>(std::exception &amp;e)</span><br><span class="line">    &#123;</span><br><span class="line">        cerr &lt;&lt; <span class="string">&quot;Exception: &quot;</span> &lt;&lt; e.<span class="built_in">what</span>() &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">Client::RsaDecrypt</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">//加载错误信息</span></span><br><span class="line">    <span class="built_in">SSL_load_error_strings</span>();</span><br><span class="line">    <span class="comment">//加载错误信息</span></span><br><span class="line">    <span class="built_in">ERR_load_crypto_strings</span>();</span><br><span class="line">    vector&lt;<span class="keyword">unsigned</span> <span class="keyword">char</span>&gt; out;</span><br><span class="line">    <span class="keyword">try</span></span><br><span class="line">    &#123;</span><br><span class="line">        RSA *rsa = <span class="built_in">RSA_new</span>();</span><br><span class="line">        BIO *keybio;</span><br><span class="line">        keybio = <span class="built_in">BIO_new_mem_buf</span>((<span class="keyword">unsigned</span> <span class="keyword">char</span> *)key.<span class="built_in">c_str</span>(), <span class="number">-1</span>);</span><br><span class="line">        rsa = <span class="built_in">PEM_read_bio_RSAPrivateKey</span>(keybio, &amp;rsa, <span class="literal">NULL</span>, <span class="literal">NULL</span>);</span><br><span class="line">        <span class="keyword">int</span> len = <span class="built_in">RSA_size</span>(rsa);</span><br><span class="line">        out.<span class="built_in">resize</span>(len);</span><br><span class="line">        <span class="keyword">int</span> ret = <span class="built_in">RSA_private_decrypt</span>(content.<span class="built_in">size</span>(), (<span class="keyword">const</span> <span class="keyword">unsigned</span> <span class="keyword">char</span>*)content.<span class="built_in">c_str</span>(), &amp;out[<span class="number">0</span>], rsa, RSA_PKCS1_PADDING);</span><br><span class="line">        <span class="keyword">if</span> (ret &lt;= <span class="number">0</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            out.<span class="built_in">resize</span>(<span class="number">0</span>);</span><br><span class="line">            cout &lt;&lt; <span class="string">&quot;Failure.&quot;</span> &lt;&lt; endl;</span><br><span class="line">            </span><br><span class="line">            <span class="comment">//获取最新的错误码</span></span><br><span class="line">            <span class="keyword">unsigned</span> <span class="keyword">long</span> errorcode = <span class="built_in">ERR_peek_last_error</span>();</span><br><span class="line">            cout &lt;&lt; <span class="string">&quot;Error Code:&quot;</span> &lt;&lt; errorcode &lt;&lt; endl;</span><br><span class="line">            <span class="keyword">char</span> errmsg[<span class="number">1024</span>] = &#123;<span class="number">0</span>&#125;;</span><br><span class="line">            <span class="keyword">char</span> *tmp = <span class="literal">NULL</span>;</span><br><span class="line">            <span class="comment">//获取和打印错误信息</span></span><br><span class="line">            tmp = <span class="built_in">ERR_error_string</span>(errorcode,errmsg);</span><br><span class="line">            cout &lt;&lt; errmsg &lt;&lt; endl;</span><br><span class="line">        &#125;<span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line">            string <span class="built_in">s</span>(out.<span class="built_in">begin</span>(),out.<span class="built_in">end</span>());</span><br><span class="line">            cout &lt;&lt; <span class="string">&quot;Success : &quot;</span> &lt;&lt; s &lt;&lt; endl;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">BIO_free_all</span>(keybio);</span><br><span class="line">        <span class="built_in">RSA_free</span>(rsa);</span><br><span class="line">    &#125;<span class="built_in"><span class="keyword">catch</span></span>(std::exception&amp; e)</span><br><span class="line">    &#123;</span><br><span class="line">        out.<span class="built_in">resize</span>(<span class="number">0</span>);</span><br><span class="line">        cout &lt;&lt; e.<span class="built_in">what</span>() &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">bool</span> <span class="title">Client::base64Decode</span><span class="params">(<span class="keyword">const</span> string&amp; input, string&amp; output)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">typedef</span> boost::archive::iterators::transform_width&lt;boost::archive::iterators::binary_from_base64&lt;string::const_iterator&gt;, <span class="number">8</span>, <span class="number">6</span>&gt; Base64DecodeIterator;</span><br><span class="line">    stringstream result;</span><br><span class="line">    <span class="keyword">try</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">copy</span>(<span class="built_in">Base64DecodeIterator</span>(input.<span class="built_in">begin</span>()) , <span class="built_in">Base64DecodeIterator</span>(input.<span class="built_in">end</span>()), ostream_iterator&lt;<span class="keyword">char</span>&gt;(result));</span><br><span class="line">    &#125;<span class="built_in"><span class="keyword">catch</span></span>(...)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="comment">//Cleanup:</span></span><br><span class="line">    std::string data = result.<span class="built_in">str</span>();</span><br><span class="line">    <span class="keyword">int</span> datasize = data.<span class="built_in">size</span>();</span><br><span class="line"></span><br><span class="line">    output = result.<span class="built_in">str</span>();</span><br><span class="line">    <span class="keyword">return</span> !output.<span class="built_in">empty</span>();</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//翻译过来的jsencrypt : base64tohex</span></span><br><span class="line"><span class="function">string <span class="title">Client::b64tohex</span><span class="params">(<span class="keyword">const</span> string&amp; input)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> k = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> slop,v;</span><br><span class="line">    vector&lt;<span class="keyword">unsigned</span> <span class="keyword">char</span>&gt; vs;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i&lt; input.<span class="built_in">size</span>(); i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span>(input[i] == b64pad) <span class="keyword">break</span>;</span><br><span class="line">        v = b64map.<span class="built_in">find_first_of</span>(input[i],<span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(v &lt; <span class="number">0</span>) <span class="keyword">continue</span>;</span><br><span class="line">        <span class="keyword">if</span>( k == <span class="number">0</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            vs.<span class="built_in">push_back</span>(BI_RM.<span class="built_in">at</span>(v &gt;&gt; <span class="number">2</span>));</span><br><span class="line">            slop = v &amp; <span class="number">3</span>;</span><br><span class="line">            k = <span class="number">1</span>;</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span>(k == <span class="number">1</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            vs.<span class="built_in">push_back</span>(BI_RM.<span class="built_in">at</span>((slop &lt;&lt; <span class="number">2</span>) |(v &gt;&gt; <span class="number">4</span>)));</span><br><span class="line">            slop = v &amp; <span class="number">0xf</span>;</span><br><span class="line">            k = <span class="number">2</span>;</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span>(k == <span class="number">2</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            vs.<span class="built_in">push_back</span>(BI_RM.<span class="built_in">at</span>(slop));</span><br><span class="line">            vs.<span class="built_in">push_back</span>(BI_RM.<span class="built_in">at</span>(v &gt;&gt; <span class="number">2</span>));</span><br><span class="line">            slop = v &amp; <span class="number">3</span>;</span><br><span class="line">            k = <span class="number">3</span>;</span><br><span class="line">        &#125;<span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line">            vs.<span class="built_in">push_back</span>(BI_RM.<span class="built_in">at</span>((slop &lt;&lt; <span class="number">2</span>)|(v &gt;&gt; <span class="number">4</span>)));</span><br><span class="line">            vs.<span class="built_in">push_back</span>(BI_RM.<span class="built_in">at</span>(v &amp; <span class="number">0xf</span>));</span><br><span class="line">            k = <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function">string <span class="title">res</span><span class="params">(vs.begin(),vs.end())</span></span>;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>联调前端输出如下，前端是在hex2b64里加了日志输出的：</p>
<blockquote>
<p>before hex2b64: 1424343c15c7345163a7a4f8a19b0067fa309ae2e1ea6cc96195e1aeb021a2080c5231c2331a1b054114c07f3c8906e7085049302d53fa2d3535d9b0eeb4d052682bf53c1b6289c405fb901424a147a8c9d7b3e9736facd23eeb6bd7bfb8d81632ae64fa09b04722b0ed21efa6abb39d2a3cecea6fef618d2cf2be75ee25d534 </p>
<p>after hex2b64: FCQ0PBXHNFFjp6T4oZsAZ/owmuLh6mzJYZXhrrAhoggMUjHCMxobBUEUwH88iQbnCFBJMC1T+i01Ndmw7rTQUmgr9TwbYonEBfuQFCShR6jJ17Ppc2+s0j7ra9e/uNgWMq5k+gmwRyKw7SHvpquznSo87Opv72GNLPK+de4l1TQ= </p>
<p>AESKey :  g9unnHKOXIj36Ee3</p>
</blockquote>
<p>服务端输出：</p>
<blockquote>
<p>addr:0.0.0.0<br>port:8888<br>client:192.168.2.18<br>Read 886bytes from client complete.<br>Read 172bytes from client complete.<br>Key : —–BEGIN RSA PRIVATE KEY—–<br>MIICXAIBAAKBgGx6zMVC1v2r5sUSoD1udXKmJD6hTItGa+JElo5LB6xIszcWpEAq<br>Zk/7Opg8WNvaYePdu+muwKrHf7K1yBqFeIshKFs5fEEwDvOyB6P3E3nGFF/ghMVK<br>Cf75MJoHVB/WkIpavVC7ekph9A7w7yM04qe/UW/4jNu8YVSwGLkCJEsrAgMBAAEC<br>gYAMs1/wJIA5WPv+zMx4BMu5bZxGvOnSUJ9m8XLTHBO85xIcfAkk/hHWgWp90mrw<br>6qOVYyuSE4S5OfxIdyIDgOb48+nCIOIdSkpkS7xHbB1VFEoRjcVtoKzQjxQO71tH<br>cq0DBTh2ITjcKfrL/mJO7Lju+3r79WaRuv3v2TRvRi7uGQJBALchorA+6VmCpsD3<br>q25J7hjUJsW5yWZb4uQ+FPsyRXdzkXQnpQYnpjbU3MYkkaHNhpbzgWN9eNi2wdch<br>A653lBUCQQCXpOWfWge33TAk/ZUHz62WQiFJzZKwpvZIxiU/CcVal/6ZIZ60/VE7<br>RW6EIRqZMV13LFa7JNW1ZuJIKNZNj/I/AkEAjFHRfoo18sgRTbp4OMGdFpk4PDjn<br>AO9XItwO54rVf3ml8gKOh/DJgyoHICvVCs2YWwGqGrmBZ0xhqp05XO1zIQJAL56U<br>jOnUqqRGzhbjicRpmlnB4k8v1VFY3Zl7cMQ8uSopxSSNlgBGVfqDrfJHS/v4gcfm<br>pHX4tjJMtKQ+R7UAOQJBALLBwYhZ/vic6DcQTWJIZOy/mnJYh8ijqi0CD/5JhoPD<br>Q7mRZIyGEX26KUSNteCGwBE5DNy8lhjXIk2PY0nIY64=<br>—–END RSA PRIVATE KEY—–<br>Content : 1424343c15c7345163a7a4f8a19b0067fa309ae2e1ea6cc96195e1aeb021a2080c5231c2331a1b054114c07f3c8906e7085049302d53fa2d3535d9b0eeb4d052682bf53c1b6289c405fb901424a147a8c9d7b3e9736facd23eeb6bd7bfb8d81632ae64fa09b04722b0ed21efa6abb39d2a3cecea6fef618d2cf2be75ee25d534<br>Failure.<br>Error Code:67522668<br>error:0406506C:rsa routines:RSA_EAY_PRIVATE_DECRYPT:data greater than mod len<br>Exception: read_some: End of file</p>
</blockquote>
<p>所以现在纯粹是内容解密有问题了，密文内容过长。</p>
<p>这篇有点多，开个下一篇。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/c/" rel="tag"># c++</a>
              <a href="/tags/aes/" rel="tag"># aes</a>
              <a href="/tags/rsa/" rel="tag"># rsa</a>
              <a href="/tags/nodejs/" rel="tag"># nodejs</a>
              <a href="/tags/websocket/" rel="tag"># websocket</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/06/29/winmongocxx/" rel="prev" title="VS2017 调试 Mongocxx">
      <i class="fa fa-chevron-left"></i> VS2017 调试 Mongocxx
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/07/13/rsafirstresult/" rel="next" title="cryptjs vs openssl 加解密(下篇)">
      cryptjs vs openssl 加解密(下篇) <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Preface"><span class="nav-number">1.</span> <span class="nav-text">Preface</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Reference"><span class="nav-number">2.</span> <span class="nav-text">Reference</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Contents"><span class="nav-number">3.</span> <span class="nav-text">Contents</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%89%8D%E7%AB%AF"><span class="nav-number">3.1.</span> <span class="nav-text">前端</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#RSA%E5%BA%93"><span class="nav-number">3.1.1.</span> <span class="nav-text">RSA库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AES%E5%BA%93"><span class="nav-number">3.1.2.</span> <span class="nav-text">AES库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B5%8B%E8%AF%95%E7%94%A8%E4%BE%8B"><span class="nav-number">3.1.3.</span> <span class="nav-text">测试用例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%8D%E5%8A%A1%E7%AB%AF"><span class="nav-number">3.2.</span> <span class="nav-text">服务端</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="ado" src="/images/avatar.png">
  <p class="site-author-name" itemprop="name">ado</p>
  <div class="site-description" itemprop="description">me, robot.</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">94</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">60</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/adoontheway" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;adoontheway" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/adoontheway" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;adoontheway" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-github"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="http://cnblogs.com/adoontheway" title="Cnblogs → http:&#x2F;&#x2F;cnblogs.com&#x2F;adoontheway" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-cnblogs"></i>Cnblogs</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://legacy.gitbook.com/@adobeattheworld" title="Gitbook → https:&#x2F;&#x2F;legacy.gitbook.com&#x2F;@adobeattheworld" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-gitbook"></i>Gitbook</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ado</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="external nofollow noopener noreferrer" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="external nofollow noopener noreferrer" target="_blank">NexT.Muse</a> 强力驱动
  </div>



        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//fastly.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  











<script>
document.querySelectorAll('.pdfobject-container').forEach(element => {
  let url = element.dataset.target;
  let pdfOpenParams = {
    navpanes : 0,
    toolbar  : 0,
    statusbar: 0,
    pagemode : 'thumbs',
    view     : 'FitH'
  };
  let pdfOpenFragment = '#' + Object.entries(pdfOpenParams).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join('&');
  let fullURL = `/lib/pdf/web/viewer.html?file=${encodeURIComponent(url)}${pdfOpenFragment}`;

  if (NexT.utils.supportsPDFs()) {
    element.innerHTML = `<embed class="pdfobject" src="${url + pdfOpenFragment}" type="application/pdf" style="height: ${element.dataset.height};">`;
  } else {
    element.innerHTML = `<iframe src="${fullURL}" style="height: ${element.dataset.height};" frameborder="0"></iframe>`;
  }
});
</script>


<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//unpkg.com/mermaid@8.14.0/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : '',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

</body>
</html>
